<?php

namespace catchAdmin\externalGoods\controller;

use catchAdmin\externalGoods\model\Category as externalCategoryModel;
use catchAdmin\externalGoods\model\DisabledCategories;
use catchAdmin\externalGoods\service\CategoryService as externalCategoryService;
use catcher\base\CatchRequest as Request;
use houniao\api\v1\Areas;
use think\Request as ThinkRequest;
use catcher\CatchAdmin;
use catcher\CatchAuth;
use catcher\CatchResponse;
use houniao\api\v1\Goods as GoodsApi;

class Category extends CatchAdmin
{
    protected $disabledCategoriesModel;
    protected $redis;
    protected $redisKey = 'disabled_categories';

    public function __construct(externalCategoryModel $externalCategoryModel, DisabledCategories $disabledCategoriesModel)
    {
        $this->externalCategoryModel = $externalCategoryModel;
        $this->disabledCategoriesModel = $disabledCategoriesModel;
        
        // 初始化Redis连接
        $this->redis = new \Redis();
        $this->redis->connect('127.0.0.1', 6379);
        $this->redis->auth(config('cache.stores.redis.password'));
    }

    //同步
    public function sync(CatchAuth $auth, Request $request)
    {
        //$params = $request->post('lists');
        $categoryService = new externalCategoryService();

        //这里判断同步的是哪里的供应链
        $params = (new GoodsApi())->category()['data'];

        $result = $categoryService->sync($params);

        return $result;
    }

    //列表
    public function index(CatchAuth $auth,Request $request){
        //$params = $request->filterEmptyField()->param();
        $categoryService = new externalCategoryService();
        $result = $categoryService->getTreeList();

        return CatchResponse::success($result);
    }

    /**
     * 设置禁用分类
     */
    public function setDisableCategories(CatchAuth $auth, Request $request)
    {
        $categoryIds = $request->post('category_ids', []);
        
        try {
            // 保存到数据库
            $this->disabledCategoriesModel->setDisabledCategories($categoryIds, $auth->user()['id']);
            
            // 同步到Redis
            $this->redis->set($this->redisKey, json_encode($categoryIds));
            
            return CatchResponse::success();
        } catch (\Exception $e) {
            return CatchResponse::fail('设置禁用分类失败: ' . $e->getMessage());
        }
    }

    /**
     * 获取禁用分类
     */
    public function getDisableCategories(CatchAuth $auth)
    {
        try {
            $categoryService = new externalCategoryService();
            $categoryIds = $categoryService->getDisabledCategories();
            return CatchResponse::success($categoryIds);
        } catch (\Exception $e) {
            return CatchResponse::fail($e->getMessage());
        }
    }
}